package com.zy.servlet.shop;

import com.google.gson.Gson;
import com.zy.entity.Shop;
import com.zy.service.GetShopService;
import com.zy.service.impl.GetShopServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import com.google.gson.JsonObject;

@WebServlet("/getShops")
public class GetShopServlet extends HttpServlet {
    private GetShopService getShopService = new GetShopServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String pageParam = req.getParameter("page");
        int page = (pageParam != null) ? Integer.parseInt(pageParam) : 1;
        int pageSize = 5;
        int start = (page - 1) * pageSize;
        List<Shop> allShops = getShopService.getAllShops();
        int totalShops = allShops.size();
        List<Shop> shops = allShops.subList(start, Math.min(start + pageSize, totalShops));
        JsonObject jsonResponse = new JsonObject();
        jsonResponse.addProperty("totalShops", totalShops);
        jsonResponse.add("shops", new Gson().toJsonTree(shops));
        out.print(jsonResponse.toString());
        out.flush();
    }
} 